package com.shanzhu.book.service.impl;

import com.shanzhu.book.mapper.BorrowMapper;
import com.shanzhu.book.mapper.NoticeMapper;
import com.shanzhu.book.model.Notice;
import com.shanzhu.book.service.NoticeService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class NoticeServiceImpl implements NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private BorrowMapper borrowMapper;


    @Override
    public void saveNotice(String token, Notice notice) {
        // 设置redisTemplate对象key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // key是token，value是用户保存到redis中，超时时间1小时
        redisTemplate.opsForValue().set(token, notice, 1, TimeUnit.HOURS);
    }

    @Override
    public Notice getNotice(String token) {
        // 根据token得到notice
        return (Notice) redisTemplate.opsForValue().get(token);
    }

    @Override
    public void removeNotice(String token) {
        // 移除token
        redisTemplate.delete(token);
    }



    @Override
    public Integer getCount() {
        return noticeMapper.selectCount();
    }

    @Override
    public List<Notice> queryNotices() {
        return noticeMapper.selectAll();
    }

    @Override
    public int getSearchCount(Map<String, Object> params) {
        return noticeMapper.selectCountBySearch(params);
    }

    @Override
    public List<Notice> searchNoticesByPage(Map<String, Object> params) {
        return noticeMapper.selectBySearch(params);
    }

    @Override
    public Integer addNotice(Notice notice) {
        return noticeMapper.insertSelective(notice);
    }

    @Override
    public Integer deleteNotice(Notice notice) {
//        if(notice.getNoticeId() == 1) return -2;
        Map<String, Object> map = new HashMap<>();
        map.put("noticeid", notice.getNoticeId());
        if(borrowMapper.selectCountBySearch(map) > 0) {
            return -1;
        }
        return noticeMapper.deleteByPrimaryKey(notice.getNoticeId());
    }

    @Override
    public Integer deleteNotices(List<Notice> notices) {
        int count = 0;
        for(Notice notice : notices) {
            count += deleteNotice(notice);
        }
        return count;
    }

    @Override
    public Integer updateNotice(Notice notice) {
        return noticeMapper.updateByPrimaryKeySelective(notice);
    }

}
